import { Injectable } from '@angular/core';

import { Observable, of } from 'rxjs';
import { mergeMap, catchError } from 'rxjs/operators';

import { HttpServer } from '@core/net/http-server';
import { UrlManager } from '@shared/url/url.manager';
import { Constant } from '@core/constant';

import { SettingsService } from '@core/settings/settings.service';
import { TokenService } from '@core/auth/token/token.service';
import { TabsService } from '../../layout/tabs/tabs.service';


@Injectable()
export class SystemUserService {

  constructor(
    private http: HttpServer,
    private settings: SettingsService,
    private tokenService: TokenService,
    private tabsService: TabsService
  ) { }

  getUserInfo(): Observable<any> {
    return this.http.get(UrlManager.user.getUserInfo, {})
      .pipe(
        mergeMap(data => {
          return of({
            name: data.account,
            logintype: data.loginType
          });
        })
      );
  }

  logout(): Observable<boolean> {
    this.settings.setLayout('spinning', true);
    return this.http.get(UrlManager.user.logoutUrl, {})
      .pipe(
        catchError(err => {
          // 退出接口异常时照常退出
          // this.clearLoginMsg();
          this.settings.setLayout('spinning', false);
          return err;
        }),
        mergeMap(data => {
          this.clearLoginMsg();
          this.settings.setLayout('spinning', false);
          return of(data);
        })
      );
  }

  clearLoginMsg(): void {
    this.tokenService.clear();
    this.tabsService.clear();
    localStorage.removeItem(Constant.APP_KEY);
    localStorage.removeItem(Constant.USER_KEY);
    localStorage.removeItem(Constant.MENU_KEY);
  }
}
